package com.rjj.wlqq.exportExcel;

import com.jfinal.plugin.activerecord.Record;
import com.rjj.wlqq.tool.date.DateUtil;
import com.rjj.wlqq.tool.excel.excelOne.ExcelExportUtil;
import com.rjj.wlqq.tool.excel.excelOne.Pair;
import com.rjj.wlqq.tool.excel.excelOne.SheetData;
import com.rjj.wlqq.tool.excel.interfaces.IExcel;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
public class ExcelController {


    /**
     * 返回html模板.
     * 跳转到excel.html页面
     */
    @RequestMapping("/excel")
    public String helloHtml(Map<String,Object> map){
 
       map.put("hello","from TemplateController.helloHtml");
       map.put("list", initDataList());

       return"/exportExcel/excel";
    }
    
    
    /**
     * @PathVariable 路径访问时候使用这个取值
     * @param request
     * @param response
     * @param id
     */
    @RequestMapping("/ex/{id}")
    public void ex(HttpServletRequest request, HttpServletResponse response, @PathVariable Integer id) {

		List<Map<String,Object>> dataList = initDataList();
		
		//设置excel表头 实体类中的属性和表格中的中文对应
		Pair pair0 = new Pair("id","id");
		Pair pair1 = new Pair("userName","用户名称");
		Pair pair2 = new Pair("pwd","用户密码");
		Pair pair3 = new Pair("createTime","创建时间");
		List<Pair> titles = new ArrayList<>();
		titles.add(pair0);
		titles.add(pair1);
		titles.add(pair2);
		titles.add(pair3);

		//接口中作出过滤
		IExcel iExcel = new IExcel() {
			
			@Override
			public String filterValue(String filed, String val) {
				//把时间过滤了
				if("createTime".equals(filed)) {
					val =  DateUtil.format(DateUtil.parse(val));
				}
				return val;
			}

			@Override
			public String[] setSheetName() {
				return new String[] {"数据1","数据2"};
			}
		};
		ExcelExportUtil.getInstance().exportByMap(response, request, "数据库数据导出", iExcel, new SheetData(titles,dataList),new SheetData(titles,dataList) );
    }


    /**
	 * 数据
    */
    public List<Map<String,Object>> initDataList(){
		List<Map<String,Object>> list = new ArrayList<>();
    	Record record = new Record();
    	record.set("id",1)
				.set("userName","rjj")
				.set("pwd","231231")
				.set("createTime",new Date());
    	list.add(record.getColumns());
    	record = new Record();
		record.set("id",1)
				.set("userName","rjj")
				.set("pwd","231231")
				.set("createTime",new Date());
		list.add(record.getColumns());
    	return list;
	}
}